package forum.client;

import forum.client.controllerlayer.*;
import forum.client.ui.*;
import forum.client.ui.events.ForumTreeErrorEvent;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.swing.*;


/**
 *
 * @author Mirsky
 */
public class MainView extends javax.swing.JFrame {

    private static final long serialVersionUID = 1612105385858246544L;
    private ExecutorService m_pool = Executors.newCachedThreadPool();
    private ControllerHandler m_pipe;
    //private Component myself;
    private UsersList dialog;
    private ForumTree tree;
    private Search searchFrame;

    /** Creates new form MainView */
    public MainView() {

        dialog = new UsersList(new javax.swing.JFrame(), true);
		dialog.addWindowListener(new java.awt.event.WindowAdapter() {
            @Override
            public void windowClosing(java.awt.event.WindowEvent e) {
                dialog.setVisible(false);
            }
        });

        m_pipe = ControllerHandlerFactory.getPipe();
        //myself = this;
        
        initComponents();        
        updateView();
        
        this.setTitle("BannanaForum");
        this.setLocationRelativeTo(null);
        this.setBackground(Color.WHITE);
        this.backToForum.setVisible(false);
        this.backToSearch.setVisible(false);
//        this.backButton.setVisible(false);
        
        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                exit();
            }
        });
    }

    public MainView(ForumTree t) {
        this();
        this.tree = t;
    }

    public JScrollPane getForumView(){
        return this.forumView;
    }

    public JButton getBackToSearch(){
        return this.backToSearch;
    }

    public JButton getBackToForum(){
        return this.backToForum;
    }

    public JButton getLoginButton(){
        return this.loginButton;
    }

    public synchronized void updateView() {
        
        // set greeting and status labels
        greetingLabel.setText("Hello " + m_pipe.getLoggedInUser() + " !");
        //String[] str = m_pipe.getConnectedUsers().split("\n");
        /*statusUsersLabel.setText(str[0]);
        if (str.length > 1)
            statusGuestsLabel.setText(str[1]);
        else
        	statusGuestsLabel.setText("");
        */
        // show buttons according to permission
    	switch(ForumTree.userType){
        case ADMIN:
        	addMessageButton.setVisible(true);
        	logoffButton.setVisible(true);
        	demoteButton.setVisible(true);
        	promoteButton.setVisible(true);
            adminLabel.setVisible(true);
        	break;
        case MODERATOR:
        	addMessageButton.setVisible(true);
        	logoffButton.setVisible(true);
        	demoteButton.setVisible(false);
        	promoteButton.setVisible(false);
            adminLabel.setVisible(false);
        	break;
        case LOGGEDINUSER:
        	addMessageButton.setVisible(true);
        	logoffButton.setVisible(true);
        	demoteButton.setVisible(false);
        	promoteButton.setVisible(false);
            adminLabel.setVisible(false);
        	break;
        default:
        	addMessageButton.setVisible(false);
        	logoffButton.setVisible(false);
        	demoteButton.setVisible(false);
        	promoteButton.setVisible(false);
            adminLabel.setVisible(false);
        	break;
        }

        this.repaint();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        searchButtonGroup = new javax.swing.ButtonGroup();
        forumView = new javax.swing.JScrollPane();
        buttonsPanel = new javax.swing.JPanel();
        greetingLabel = new javax.swing.JLabel();
        registerButton = new javax.swing.JButton();
        loginButton = new javax.swing.JButton();
        addMessageButton = new javax.swing.JButton();
        searchButton = new javax.swing.JButton();
        demoteButton = new javax.swing.JButton();
        logoffButton = new javax.swing.JButton();
        promoteButton = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        adminLabel = new javax.swing.JLabel();
        searchTextField = new javax.swing.JTextField();
        contentRadioButton = new javax.swing.JRadioButton();
        authorRadioButton = new javax.swing.JRadioButton();
        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        backToForum = new javax.swing.JButton();
        backToSearch = new javax.swing.JButton();
        refreshButton = new javax.swing.JButton();
        this.searchButtonGroup.add(this.authorRadioButton);
        this.authorRadioButton.setSelected(true);
        this.searchButtonGroup.add(this.contentRadioButton);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        greetingLabel.setText("jLabel1");

        registerButton.setIcon(new javax.swing.ImageIcon(".\\images\\table_edit.png")); // NOI18N
        registerButton.setText("Register");
        registerButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                registerButtonActionPerformed(evt);
            }
        });

        loginButton.setIcon(new javax.swing.ImageIcon(".\\images\\login.jpg")); // NOI18N
        loginButton.setText("Login");
        loginButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                loginButtonActionPerformed(evt);
            }
        });

        addMessageButton.setIcon(new javax.swing.ImageIcon(".\\images\\addMessage.jpg")); // NOI18N
        addMessageButton.setText("Add Message");
        addMessageButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addMessageButtonActionPerformed(evt);
            }
        });

        searchButton.setIcon(new javax.swing.ImageIcon(".\\images\\search2.jpg")); // NOI18N
        searchButton.setText("Search");
        searchButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchButtonActionPerformed(evt);
            }
        });

        demoteButton.setText("Demote");
        demoteButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                demoteButtonActionPerformed(evt);
            }
        });

        logoffButton.setIcon(new javax.swing.ImageIcon(".\\images\\logoff.jpg")); // NOI18N
        logoffButton.setText("Logoff");
        logoffButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                logoffButtonActionPerformed(evt);
            }
        });

        promoteButton.setText("Promote");
        promoteButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                promoteButtonActionPerformed(evt);
            }
        });

        adminLabel.setText("Admin interface:");

        contentRadioButton.setText("By Content");

        authorRadioButton.setSelected(true);
        authorRadioButton.setText("By Author");

        jLabel1.setText("Search:");

        jButton1.setIcon(new javax.swing.ImageIcon(".\\images\\system-users.png")); // NOI18N
        jButton1.setText("Connected Users");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        backToForum.setIcon(new javax.swing.ImageIcon(".\\images\\home.jpg")); // NOI18N
        backToForum.setText("Back to Forum");
        backToForum.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                backToForumActionPerformed(evt);
            }
        });

        backToSearch.setText("Back to Search Results");
        backToSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                backToSearchActionPerformed(evt);
            }
        });

        refreshButton.setIcon(new javax.swing.ImageIcon(".\\images\\refresh.jpg")); // NOI18N
        refreshButton.setText("Refresh");
        refreshButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                refreshButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout buttonsPanelLayout = new javax.swing.GroupLayout(buttonsPanel);
        buttonsPanel.setLayout(buttonsPanelLayout);
        buttonsPanelLayout.setHorizontalGroup(
            buttonsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(buttonsPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(buttonsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(buttonsPanelLayout.createSequentialGroup()
                        .addComponent(addMessageButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(backToForum)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(backToSearch)
                        .addGap(18, 18, 18)
                        .addComponent(refreshButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 169, Short.MAX_VALUE)
                        .addComponent(adminLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(promoteButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(demoteButton))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, buttonsPanelLayout.createSequentialGroup()
                        .addGroup(buttonsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 428, Short.MAX_VALUE)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, buttonsPanelLayout.createSequentialGroup()
                                .addComponent(registerButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(loginButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(logoffButton)
                                .addGap(18, 18, 18)
                                .addComponent(jButton1)))
                        .addGap(18, 18, 18)
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(searchTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(authorRadioButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(contentRadioButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(searchButton))
                    .addComponent(greetingLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        buttonsPanelLayout.setVerticalGroup(
            buttonsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(buttonsPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(greetingLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(buttonsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(registerButton)
                    .addComponent(loginButton)
                    .addComponent(logoffButton)
                    .addComponent(searchButton)
                    .addComponent(contentRadioButton)
                    .addComponent(authorRadioButton)
                    .addComponent(searchTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(jButton1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(buttonsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(demoteButton)
                    .addComponent(promoteButton)
                    .addComponent(adminLabel)
                    .addComponent(addMessageButton)
                    .addComponent(backToForum)
                    .addComponent(backToSearch)
                    .addComponent(refreshButton))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(buttonsPanel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(forumView, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 926, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(buttonsPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(forumView, javax.swing.GroupLayout.DEFAULT_SIZE, 331, Short.MAX_VALUE)
                .addGap(50, 50, 50))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void registerButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_registerButtonActionPerformed
        JFrame registerFrame = new Register(this);
        registerFrame.setVisible(true);
        this.setVisible(false);
    }//GEN-LAST:event_registerButtonActionPerformed

    private void loginButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loginButtonActionPerformed
        JFrame loginFrame = new Login(this);
        loginFrame.setVisible(true);
        this.setVisible(false);
    }//GEN-LAST:event_loginButtonActionPerformed

    private void logoffButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_logoffButtonActionPerformed
        SwingWorker<String[], Void> logoffWorker = new SwingWorker<String[], Void>(){
            @Override
            protected String[] doInBackground() {
                return m_pipe.logoff(false);
            }
        };
        m_pool.execute(logoffWorker);
         try {
            String[] ans = (String[])logoffWorker.get();
            if (ans[0].equals("succ")){
                //m_pipe.refreshForum(m_pool);
                updateView();
                this.loginButton.setVisible(true);
            } else{
                m_pipe.notifyObservers(new ForumTreeErrorEvent(ans[1], this));
            }
        } catch (InterruptedException ex) {}
        catch (ExecutionException ex) {
            m_pipe.notifyObservers(new ForumTreeErrorEvent("Execution exception."));
        }
        
        
    }//GEN-LAST:event_logoffButtonActionPerformed

    private void addMessageButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addMessageButtonActionPerformed
        JFrame addMessageFrame = new AddMessage(this);
        addMessageFrame.setVisible(true);
        this.setVisible(false);
    }//GEN-LAST:event_addMessageButtonActionPerformed

    private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchButtonActionPerformed
        String searchBy="";
        if (searchTextField.getText().length()==0) {
            JOptionPane.showMessageDialog(this,
			    "Please enter a search key before hitting \"search\".",
			    "Operation failed.",
			    JOptionPane.WARNING_MESSAGE);
            return;
        }
        if (authorRadioButton.isSelected())
                        searchBy = "author";
                else
                        searchBy = "content";
        searchFrame = new Search(this, searchTextField.getText(), searchBy, tree);
        searchFrame.setVisible(true);
        this.setVisible(false);
//        this.backButton.setVisible(true);
    }//GEN-LAST:event_searchButtonActionPerformed

    private void promoteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_promoteButtonActionPerformed
    	
        dialog.setListItems(true);
        dialog.setVisible(true);
        
    }//GEN-LAST:event_promoteButtonActionPerformed

    private void demoteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_demoteButtonActionPerformed
        
                dialog.setListItems(false);
                dialog.setVisible(true);
        
    }//GEN-LAST:event_demoteButtonActionPerformed

    private void backButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backButtonActionPerformed


    }//GEN-LAST:event_backButtonActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        JFrame connectedUsersFrame = new ConnectedUsersForm(this);
        connectedUsersFrame.setVisible(true);
    }//GEN-LAST:event_jButton1ActionPerformed

    private void backToForumActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backToForumActionPerformed

        m_pipe.refreshForum(m_pool);
        this.backToForum.setVisible(false);
        this.backToSearch.setVisible(false);
    }//GEN-LAST:event_backToForumActionPerformed

    private void backToSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backToSearchActionPerformed
        this.setVisible(false);
        searchFrame.setVisible(true);
    }//GEN-LAST:event_backToSearchActionPerformed

    private void refreshButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refreshButtonActionPerformed
        this.m_pipe.refreshForum(m_pool);
    }//GEN-LAST:event_refreshButtonActionPerformed
    
    /**
     * used when the x is pressed.
     */
    private void exit(){
    	m_pipe.logoff(true);
    	this.setVisible(false);
    	dispose();
    	System.exit(0);
    }
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addMessageButton;
    private javax.swing.JLabel adminLabel;
    private javax.swing.JRadioButton authorRadioButton;
    private javax.swing.JButton backToForum;
    private javax.swing.JButton backToSearch;
    private javax.swing.JPanel buttonsPanel;
    private javax.swing.JRadioButton contentRadioButton;
    private javax.swing.JButton demoteButton;
    private javax.swing.JScrollPane forumView;
    private javax.swing.JLabel greetingLabel;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JButton loginButton;
    private javax.swing.JButton logoffButton;
    private javax.swing.JButton promoteButton;
    private javax.swing.JButton refreshButton;
    private javax.swing.JButton registerButton;
    private javax.swing.JButton searchButton;
    private javax.swing.ButtonGroup searchButtonGroup;
    private javax.swing.JTextField searchTextField;
    // End of variables declaration//GEN-END:variables

}
